package cn.fancy.sdk.login.view;

import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.DeleteUserDialog;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.TipMessSingle;
import org.w3c.dom.Text;

/*
 * 实名认证：包括输入账号密码
 */
public class RealMainCompleteView extends BaseView implements
		OnItemClickListener {
	IActivityManager activityMgr;
	private Activity ownerActivity;
	Context mContext;
	LayoutInflater inflater;
	DBHelper dbHelper;

	private EditText real_people_name, real_people_idcardnum;
	private ImageView eyeImg;
	private static EditText real_user_name, real_password;
	ClipboardManager clisign;
	SdkAsyncTask<String> RealSyncTask = null;
	
	private ArrayList<RealMainCompleteView.Account> acctArray = new ArrayList<RealMainCompleteView.Account>();
	private ArrayList<DBHelper.SDK_ACCOUNT> db_valid_accts = new ArrayList<DBHelper.SDK_ACCOUNT>();
	ArrayList<AccountHelper.Local_Account> local_valid_accts = new ArrayList<AccountHelper.Local_Account>();
	private RelativeLayout downImgLayout;
	private AccountShowAdatper adapter = null;
	private PopupWindow popupWindow = null;
	private ListView popListView = null;
	static public String staticusername, staticpassword, savepoint,
			staticdeleteusername;
	private DeleteUserDialog deleteDialog;
	static public RealMainCompleteView Viewtext;
	private static int currentpostion = 0;

	public RealMainCompleteView(Activity cActivity, IActivityManager activityMgr) {
		super(cActivity.getBaseContext(), ResUtil.getLayoutId(
				cActivity.getBaseContext(), "guild_realiden"));
		mContext = cActivity.getBaseContext();
		this.activityMgr = activityMgr;
		ownerActivity = cActivity;
		inflater = LayoutInflater.from(this.getContext());
		dbHelper = DBHelper.getInstance(this.getContext());
		clisign = (ClipboardManager) mContext
				.getSystemService(Context.CLIPBOARD_SERVICE);
		initView();

		savepoint = "0";
		Viewtext = this;
		try {
			initAccount();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initAccount() {
		// 先在本地sqlite 数据库中检测是否有用户名存在
		db_valid_accts = dbHelper.getAllValidAccounts();
		local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext,true);
		AccountHelper.Local_Account account = AccountHelper
				.getLastestLoginAccountFromOldSdk(mContext);
		if (db_valid_accts.size() > 0) {
			DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
			real_user_name.setText(acc.user_name);
			real_password.setText(acc.user_password);
		} else if (local_valid_accts.size() > 0) {
			Local_Account temp = local_valid_accts
					.get(local_valid_accts.size() - 1);
			real_user_name.setText(temp.username);
			real_password.setText(temp.password);
		} else if (account.username != null && !"".equals(account.username)
				&& account.password != null && !"".equals(account.password)) {
			account.last_login_time = System.currentTimeMillis();
			account.isValid = AccountHelper.ACCOUNT_VALID;

			AccountHelper.updateLocalAccounts(account);
			real_user_name.setText(account.username);
			real_password.setText(account.password);
		} else {
			real_user_name.setText("");
			real_password.setText("");
		}
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		this.postInvalidate();
		updateAccount();
	}

	private void updateAccount() {
		db_valid_accts = dbHelper.getAllValidAccounts();
		if (LoginView.chooseCurrentUser == true) {
			real_user_name.setText(CommMessage.currentRealmainUserName);
			real_password.setText(CommMessage.currentRealmainPassword);
		} else if (db_valid_accts.size() > 0) {
			DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
			real_user_name.setText(acc.user_name);
			real_password.setText(acc.user_password);
		} else {
			local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext,true);
			if (local_valid_accts.size() > 0) {
				Local_Account temp = local_valid_accts.get(local_valid_accts
						.size() - 1);
				real_user_name.setText(temp.username);
				real_password.setText(temp.password);
			}
		}
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
	}

	private void initView() {
		real_user_name = (EditText) this.findViewById(ResUtil.getId(mContext,
				"guild_usernmae_main_line"));
		real_user_name.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
		real_user_name
				.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

		real_password = (EditText) this.findViewById(ResUtil.getId(mContext,
				"guild_password_main_line"));
		real_password.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

		eyeImg = (ImageView) this.findViewById(ResUtil.getId(mContext,
				"guild_real_eye_img"));
		eyeImg.setSelected(false);
		real_password.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		eyeImg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (eyeImg.isSelected()) {
					eyeImg.setSelected(false);
					eyeImg.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_off"));
					real_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				} else {
					eyeImg.setSelected(true);
					eyeImg.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_on"));
					real_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				}
			}
		});
		real_people_name = (EditText) this.findViewById(ResUtil.getId(mContext,
				"guild_real_main_line"));
		real_people_name.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

		real_people_idcardnum = (EditText) this.findViewById(ResUtil.getId(
				mContext, "guild_real_main_prople"));
		real_people_idcardnum.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
		
		TextView ok_btn = (TextView) this.findViewById(ResUtil.getId(mContext,
			"guild_real_main_confirm"));
		ok_btn.setOnClickListener(this);
		
		ImageView cancle_btn = (ImageView) this.findViewById(ResUtil.getId(mContext,
			"guild_real_main_cancle"));
		cancle_btn.setOnClickListener(this);
		
		ImageView acctDownIV = (ImageView) this.findViewById(ResUtil.getId(mContext,
			"guild_login_down"));
		acctDownIV.setOnClickListener(this);
		downImgLayout = (RelativeLayout) this.findViewById(ResUtil.getId(
				mContext, "usernamelayout"));
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		if (vid == ResUtil.getId(mContext, "guild_real_main_confirm")) {
			doBindCodeRequest();
		} else if (vid == ResUtil.getId(mContext, "guild_real_main_cancle")) {
			activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
		} else if (vid == ResUtil.getId(mContext, "guild_login_down")) {
			popupWindowInit();
			if (popupWindow.isShowing() || 0 == acctArray.size()) {
				popupWindow.dismiss();
			} else {
				View view = (RelativeLayout) this.findViewById(ResUtil.getId(
						mContext, "usernamelayout"));
				popupWindow.showAsDropDown(view, 0, -2);
			}
		}
	}

	private void popupWindowInit() {
		int width = this.findViewById(ResUtil.getId(mContext, "layout")).getWidth();
		acctArray.clear();
		db_valid_accts = dbHelper.getAllValidAccounts();
		local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext, true);
		boolean flag = false;
		if (db_valid_accts.size() > 0) {
			flag = true;
			downImgLayout.setClickable(true);
			for (int index = 0; index < db_valid_accts.size(); index++) {
				DBHelper.SDK_ACCOUNT obj = db_valid_accts.get(index);
				acctArray.add(new Account(obj.user_name,
					obj.user_password, 1));
			}
		} else {
			flag = false;
			downImgLayout.setClickable(false);
		}

		if (local_valid_accts.size() > 0) {
			downImgLayout.setClickable(true);
			for (int index = 0; index < local_valid_accts.size(); index++) {
				Local_Account obj = local_valid_accts.get(index);

				int db_index = 0;
				for (; db_index < db_valid_accts.size(); db_index++) {
					DBHelper.SDK_ACCOUNT db_obj = db_valid_accts.get(db_index);
					if (db_obj.user_name.equals(obj.username)) {
						break;
					}
				}
				if (db_index == db_valid_accts.size())
					acctArray.add(new Account(
						obj.username, obj.password, 1));
			}
		} else {
			if (flag == false)
				downImgLayout.setClickable(false);

		}

		if (adapter == null) {
			adapter = new AccountShowAdatper(acctArray);
		} else {
			adapter.setAdapterObj(acctArray);
		}

		if (popListView == null) {
			popListView = new ListView(mContext);
		}

		popListView.setDivider(getResources().getDrawable(
				ResUtil.getDrawableId(mContext, "guild_img_line")));
		popListView.setDividerHeight(1);
		popListView.setCacheColorHint(0xffefeee8);
		popListView.setOnItemClickListener(this);
		popListView.setAdapter(adapter);

		if (popupWindow == null) {
			popupWindow = new PopupWindow(popListView, width,
					LayoutParams.WRAP_CONTENT, true);
		}

		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(getResources().getDrawable(
				ResUtil.getDrawableId(mContext, "guild_input_down")));

		popupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {

			}
		});
	}

	public void commitPeopleMessae(String username, String password,
			String peoplename, String peoplesign) {
		final Map<String, String> regMap = GuildBaseInfo.getInstance().realParamReq(
				mContext, username, password, peoplename, peoplesign, "set_idcard");

		if (regMap == null) {
			Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
			return;
		}
		RealSyncTask = new SdkAsyncTask<String>() {

			@Override
			protected String doInBackground() {
				return HttpReq.doGuildRequest(regMap);
			}

			@Override
			protected void onPostExecute(String rst) {
				activityMgr.cancelWaitingDialog();
				Log.e("RealSyncTaskrst", "RealSyncTaskrst"  + rst);

				if (TextUtils.isEmpty(rst)) {
					Toast.makeText(mContext, TipMessSingle.ten_networkerr,
							Toast.LENGTH_LONG).show();
					return;
				}
				try {
					JSONObject json = new JSONObject(rst);
					String state = json.getString("state");
					JSONObject jsonState = new JSONObject(state);
					
					int code = jsonState.getInt("code");
					Toast.makeText(mContext, jsonState.getString("msg"),
						Toast.LENGTH_LONG).show();
					if (code != 1) {
						return;
					}
					
					//String dataStr = json.optString("data");
					// 成功后要干的事情
					//activityMgr.NewpopViewFromStack();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public Activity getOwnerActivity() {
				return ownerActivity;
			}

			@Override
			protected void onCancelled() {}
		};
		RealSyncTask.execute();
		activityMgr.showWaitingDialog();
	}

	public void doBindCodeRequest() {
		final String uname = real_user_name.getText().toString().trim();
		final String upassword = real_password.getText().toString().trim();
		final String peoplename = real_people_name.getText().toString().trim();
		final String peoplesign = real_people_idcardnum.getText().toString()
				.trim();
		if(TextUtils.isEmpty(uname)){
			Toast.makeText(mContext, TipMessSingle.one_usernil,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		if(TextUtils.isEmpty(upassword)){
			Toast.makeText(mContext, TipMessSingle.one_passnil,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		if(TextUtils.isEmpty(peoplename)){
			Toast.makeText(mContext, TipMessSingle.six_namenil,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		if(TextUtils.isEmpty(peoplesign)){
			Toast.makeText(mContext, TipMessSingle.six_numbernil,
					Toast.LENGTH_LONG).show();
			return;
		}

		if (!NetworkImpl.isNetworkConnected(getContext())) {
			Toast.makeText(mContext, TipMessSingle.ten_networkerr,
					Toast.LENGTH_LONG).show();
			return;
		}

		commitPeopleMessae(uname, upassword, peoplename, peoplesign);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Account account = acctArray.get(position);
		String username = account.user_name;
		String password = account.user_password;
		real_user_name.setText(username);
		real_password.setText(password);
		LoginView.chooseCurrentUser = true;
		CommMessage.currentUserName = username;
		CommMessage.currentPassword = password;
		popupWindow.dismiss();
	}

	public class AccountShowAdatper extends BaseAdapter {

		ArrayList<RealMainCompleteView.Account> array;

		public AccountShowAdatper(ArrayList<RealMainCompleteView.Account> array) {
			this.array = array;
		}

		public void setAdapterObj(ArrayList<RealMainCompleteView.Account> array) {

			this.array = array;
		}

		@Override
		public int getCount() {
			return array.size();
		}

		@Override
		public Object getItem(int position) {
			return array.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Log.e("position", position + "");
			ViewHolder holder;
			final String curUser = array.get(position).user_name;

			if (convertView == null) {

				convertView = inflater.inflate(ResUtil.getLayoutId(mContext,
						"guild_account_list_item"), null);

				holder = new ViewHolder();

				holder.account = (TextView) convertView.findViewById(ResUtil
						.getId(mContext, "guild_account_name"));
				holder.delete = (RelativeLayout) convertView
						.findViewById(ResUtil.getId(mContext,
								"guild_account_dele"));

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.account.setText(curUser);

			String userandpassPP = curUser + "," + position + "";
			holder.delete.setTag(userandpassPP);
			holder.delete.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					
					if (arg0 != null) {
						String userpass = arg0.getTag().toString();

						String username = "";
						String passowrd = "";
						String pointsave = "0";

						String[] sourceStrArray = userpass.split(",");
						for (int i = 0; i < sourceStrArray.length; i++) {
							if (i == 0) {
								username = sourceStrArray[i];
							} else if (i == 1) {
								passowrd = sourceStrArray[i];
							} else if (i == 2) {
								pointsave = sourceStrArray[i];
							}

						}

						staticdeleteusername = username;

						savepoint = pointsave;
						staticusername = username;
						staticpassword = passowrd;
					}

					deleteDialog = new DeleteUserDialog(ownerActivity, 3);
					deleteDialog.show();
					
					if (position == 1) {
						currentpostion = 1;
					} else {
						currentpostion = 0;
					}
				}
			});
			return convertView;
		}
	}

	static public void deleteUser(RealMainCompleteView ViewContext) {
		if (ViewContext == null) {
			return;
		}
		if (ViewContext.acctArray != null) {
			Local_Account accs = new Local_Account(staticusername,
					staticpassword, 0);
			ViewContext.acctArray.remove(savepoint);
			if (ViewContext.real_user_name.getText().toString().trim()
					.equals(accs.username)) {
				if (!ViewContext.acctArray.isEmpty()) {
					if (ViewContext.acctArray.size() == 1) {
						real_user_name.setText("");
						real_password.setText("");
						LoginView.editclear();
						ViewContext.dbHelper.setAccountInvalid(staticusername);
						AccountHelper.updateLocalAccounts(accs);
						ViewContext.popupWindow.dismiss();
						ViewContext.adapter.notifyDataSetChanged();
						CommMessage.currentPassword = "";
						CommMessage.currentUserName = "";
						return;
					}
					RealMainCompleteView.Account acc = ViewContext.acctArray
							.get(1);
					if (currentpostion == 1) {
						acc = ViewContext.acctArray.get(0);
					}
					String username = acc.user_name;
					String passString = acc.user_password;
					ViewContext.real_user_name.setText(username);
					ViewContext.real_password.setText(passString);
				} else {
					ViewContext.real_user_name.setText("");
					ViewContext.real_password.setText("");
				}
			}
			// ViewContext.user_name_input.setText("");

			ViewContext.dbHelper.setAccountInvalid(staticusername);
			AccountHelper.updateLocalAccounts(accs);

			ViewContext.popupWindow.dismiss();
			// if (ViewContext.acctArray.size() == 0) {
			// ViewContext.popupWindowDismiss();
			// }
			ViewContext.adapter.notifyDataSetChanged();

			CommMessage.currentUserName = real_user_name.getText().toString();
			CommMessage.currentPassword = real_password.getText().toString();
		}
	}

	private static class ViewHolder {
		TextView account;
		RelativeLayout delete;
	}

	private static class Account {
		String user_name;
		String user_password;
		int is_valid;

		Account(String user, String pass, int isValid) {
			this.user_name = user;
			this.user_password = pass;
			this.is_valid = isValid;
		}
	}
}
